package com.monitor.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.monitor.commons.HttpTookit;
import com.monitor.commons.StringUtil;
import com.monitor.commons.enums.WhetherEnum;
import com.monitor.config.yunke.YunKeConfig;
import com.monitor.config.yunke.YunKeUtil;
import com.monitor.dao.ICustomerDao;
import com.monitor.dao.IUserDao;
import com.monitor.model.Dept;
import com.monitor.modelExt.CustomerExt;
import com.monitor.modelExt.UserExt;
import com.monitor.pubInter.AbstractBaseService;
import com.monitor.pubInter.IBaseDao;
import com.monitor.pubInter.exception.SkException;
import com.monitor.searchExt.CustomerSearchExt;
import com.monitor.searchExt.UserSearchExt;
import com.monitor.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author afeng
 * @Date 2025-03-17 10:50:14
 * @description CustomerService      客户信息
 */
@Service(value = "customerService")
@Slf4j
public class CustomerServiceImpl extends AbstractBaseService<CustomerExt, CustomerSearchExt, String> implements ICustomerService {

    @Resource(name = "customerDao")
    private ICustomerDao customerDao;
    @Resource(name = "userDao")
    private IUserDao userDao;

    @Autowired
    private YunKeUtil yunKeUtil;
    @Autowired
    private YunKeConfig yunKeConfig;

    @Override
    public IBaseDao<CustomerExt, CustomerSearchExt, String> getDao() {
        return customerDao;
    }

    @Override
    public void syncCustomerData() throws SkException {
        try {


            UserSearchExt userSearchExt = UserSearchExt.getInstance();
            userSearchExt.setGroupBy(UserExt.ID);
            List<Integer> isBindIn = new ArrayList<>();
            isBindIn.add(WhetherEnum.YES.getValue());
            userSearchExt.setIsBindIn(isBindIn);
            List<UserExt> userExts = userDao.getAllList(userSearchExt);
            if (StringUtil.isNotObjEmpty(userExts) && !userExts.isEmpty()) {
                List<String> userIds = userExts.stream().map(UserExt::getYkUserId).toList();
                //定义请求路径
                String url = yunKeConfig.getUrl() + "open/customer/getCustomersCountGroupByUserId";
                //组装请求头
                long timestamp = new Date().getTime();
                Map<String, String> headsMap = yunKeUtil.getHeadMap(timestamp);
                //组装请求参数
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("userIds", userIds);
                String res = HttpTookit.doPostHeader(url, paramsMap, headsMap);
                JSONObject resObject = JSONObject.parseObject(res);
                int num = 0;
                if (resObject.getBoolean("success")) {
                    JSONArray userCountArr = resObject.getJSONArray("data");
                    for (Object userCount : userCountArr) {
                        JSONObject userCountInfo = (JSONObject) userCount;
                        num += userCountInfo.getInteger("customerCount");
//                        for (UserExt userExt : userExts) {
//                            if (StringUtil.equal(userExt.getYkUserId(), userCountInfo.getString("userId"))) {
//                                log.info(userExt.getName() + "的数据,云客上的客户数量===" + userCountInfo.getInteger("customerCount") + "===本地数量:" + userExt.getCustomerCount());
//                                if (userCountInfo.getInteger("customerCount") > userExt.getCustomerCount()) {
//                                    customersByUserId(userExt, 1);
//                                }
//                                break;
//                            }
//                        }
                    }

                }
                log.info("客户总数:" + num);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void customersByUserId(UserExt user, int page) throws SkException {

        try {
            //定义请求路径
            String url = yunKeConfig.getUrl() + "open/customer/getCustomersByUserId";
            //组装请求头
            long timestamp = new Date().getTime();
            Map<String, String> headsMap = yunKeUtil.getHeadMap(timestamp);
            //组装请求参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("size", 100);
            paramsMap.put("page", page);
            paramsMap.put("userId", user.getYkUserId());
            String res = HttpTookit.doPostHeader(url, paramsMap, headsMap);
            log.info("用户" + user.getName() + "的数据:" + res);
            JSONObject resObject = JSONObject.parseObject(res);
            if (resObject.getBoolean("success")) {
                JSONObject dataObj = resObject.getJSONObject("data");
                int currentPage = dataObj.getInteger("pageNum");
                int totalPage = dataObj.getInteger("pages");
                JSONArray dataArr = dataObj.getJSONArray("list");
                if (StringUtil.isNotObjEmpty(dataArr) && !dataArr.isEmpty()) {
                    for (Object item : dataArr) {
                        JSONObject itemObj = JSONObject.from(item);
//                        新建用户对象
                        CustomerExt customerExt = new CustomerExt();
//                       是否存在旧数据
                        CustomerSearchExt searchExt = CustomerSearchExt.getInstance();
                        searchExt.setYkIdLike(itemObj.getString("id"));
                        List<CustomerExt> customerList = customerDao.getAllList(searchExt);
                        if (StringUtil.isNotObjEmpty(customerList) && !customerList.isEmpty()) {
                            customerExt = customerList.getFirst();
                        }
//更新数据
                        customerExt.setName(itemObj.getString("name"));
                        customerExt.setPhone(itemObj.getString("phone"));
                        customerExt.setPartnerId(itemObj.getString("partnerId"));
                        customerExt.setCreateTime(itemObj.getDate("createTime"));
                        customerExt.setYkId(itemObj.getString("id")); // 云客端客户id
                        customerExt.setYkUserId(itemObj.getString("userId")); // 云客端用户id
                        customerExt.setUserId(user.getId()); // 用户id
                        customerExt.setFollowTime(itemObj.getDate("followTime"));
                        customerExt.setLastContactTime(itemObj.getDate("lastContactTime"));
                        customerExt.setLastContactIntent(itemObj.getInteger("lastContactIntent"));
                        customerExt.setLastContactRemark(itemObj.getString("lastContactRemark"));
                        customerExt.setLastContactTag(itemObj.getString("lastContactTag"));

                        if (StringUtil.isNotObjEmpty(customerList) && !customerList.isEmpty()) {
                            customerDao.update(customerExt);
                        } else {
                            customerDao.insert(customerExt);
                        }

                    }

                    if (totalPage > currentPage) {
                        currentPage++;
                        customersByUserId(user, currentPage);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}